﻿using UnityEngine;
using System.Collections;

public class SpawnScript : MonoBehaviour {

	private float initialSpawnTime = 3.0f;
	private float spawnTimer = 3.0f;
	private float spawnTimeRemaining = 5.0f;
	
	public GameObject wall = null;
	public GameObject jumpWall = null;
	public GameObject detector = null;

	public float upperEdge = 2f;
	public float lowerEdge = -2f;

	private int wallCounter = 0;

	private GameObject counter;
	private PointScript script;

	void Start (){
		counter = GameObject.FindGameObjectWithTag ("PointCounter");
		script = (PointScript) counter.GetComponent ("PointScript");
	}
	
	void Awake()
	{
		spawnTimeRemaining = spawnTimer;
	}
	
	void FixedUpdate()
	{
		if (Input.GetKey(KeyCode.Escape))
		{
			DontDestroyOnLoad (counter);
			Application.LoadLevel ("GameOver");
		}
		spawnTimeRemaining -= Time.deltaTime;
		
		if (spawnTimeRemaining < 0.0f)
		{
			switch(getWallType()){
			case 0:
				spawnRegularWall();
				break;
			case 1:
				spawnJumpWall();
				break;
			}
		}
		adjustSpawnTime ();
	}

	void adjustSpawnTime(){
		if(spawnTimer > 0.7f){
			spawnTimer =  initialSpawnTime - (script.getCurrentPoints()/20.0f);
		}
	}

	void spawnRegularWall(){
		Vector3 newPos = transform.position;
		float random = getRandomHeight ();
		newPos.y = upperEdge + 2f;
		float gap = getRandomGap ();
		while (newPos.y > lowerEdge - 2f) {
			if(newPos.y < random && newPos.y > random - gap){
				newPos.y -= gap;
			}else{
				newPos.y -= ((GameObject)Instantiate(wall,  newPos, Quaternion.identity)).renderer.bounds.size.y;
			}
		}
		spawnDetector();
		spawnTimeRemaining = spawnTimer;
	}

	void spawnJumpWall(){
		Vector3 newPos = transform.position;
		newPos.y = upperEdge + 2f;
		while (newPos.y > lowerEdge - 2f) {
			newPos.y -= ((GameObject)Instantiate(jumpWall,  newPos, Quaternion.identity)).renderer.bounds.size.y;
		}
		spawnDetector();
		spawnTimeRemaining = spawnTimer;
	}

	void spawnDetector(){
		Vector3 newPos = transform.position;
		newPos.y = getRandomHeight();
		newPos.x += 0.1f;
		WallScript wallScript = (WallScript) ((GameObject)Instantiate(detector,  newPos, Quaternion.identity)).GetComponent("WallScript");
		wallScript.setId(wallCounter);
		wallCounter++;
	}

	float getRandomHeight(){
		return Random.Range (lowerEdge, upperEdge);
	}

	float getRandomGap(){
		return Random.Range (0.5f, 1.0f);
	}

	int getWallType(){
		if (Random.value < 0.2f) {
			return 1;
		}
		return 0;
	}
}
